package calculator.main;

import javapop.framework.ParseInput;
import javapop.framework.ParseResult;
import javapop.framework.input.StringParseInput;
import calculator.ast.Expr;
import calculator.parser.CalculatorGrammar;

public class CmdLineMain {

	public static Double evalOne(String cmd) {
		CalculatorGrammar calc = new CalculatorGrammar();
		System.out.println("> "+cmd);
		if(cmd.equals("quit")) {
			System.out.println("Good bye");
			return null;
		}
		ParseInput input = new StringParseInput(cmd);
		ParseResult<Expr> expr = calc.parse(input);
		if(expr.isError()) {
			System.err.println("Error: "+expr.asError().getErrorMessage());
			System.err.println("==> "+input.show(0,80));
			return null;
		} else {				
			try {
				double val = expr.getResult().eval();
				System.out.println(val);
				return val;
			} catch(Error e) {
				System.err.println("Error: cannot evaluate\n  ==> "+expr.toString());
				return null;
			}
		}		
	}
	
	public static void main(String...args) {
		System.out.print("Calculator (C) 2009 F. Peschanski\n");
		for(String cmd : args) {
			evalOne(cmd);
		}
	}
}
